package se.jocke.nb.log.ui;

import java.awt.Color;
import java.awt.EventQueue;
import java.io.IOException;
import java.util.List;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import org.openide.util.Exceptions;
import se.jocke.nb.log.TailListener;
import se.jocke.nb.log.model.LogViewFilter;

/**
 *
 * @author jocke
 */
public class TextPaneTailListener implements TailListener {

    private final JTextPane pane;

    private final List<LogViewFilter> filters;

    public TextPaneTailListener(JTextPane pane, List<LogViewFilter> filters) {
        this.pane = pane;
        this.filters = filters;
    }

    @Override
    public void onLine(final String line) {
        final SimpleAttributeSet attributeSet = new SimpleAttributeSet();

        for (LogViewFilter logViewFilter : filters) {
            if (logViewFilter.matches(line)) {
                StyleConstants.setForeground(attributeSet, logViewFilter.getForegroundColor());
                StyleConstants.setBackground(attributeSet, logViewFilter.getBackgroundColor());
                StyleConstants.setFontFamily(attributeSet, logViewFilter.getFont().getFamily());
                StyleConstants.setFontSize(attributeSet, logViewFilter.getFont().getSize());
                StyleConstants.setItalic(attributeSet, logViewFilter.getFont().isItalic());
                StyleConstants.setBold(attributeSet, logViewFilter.getFont().isBold());
                break;
            }
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                StyledDocument doc = pane.getStyledDocument();
                try {
                    doc.insertString(doc.getLength(), line + "\n", attributeSet);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        };

        EventQueue.invokeLater(runnable);
    }

    @Override
    public void onIOException(final IOException ioe) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Exceptions.printStackTrace(ioe);
            }
        });
    }
}
